package com.b2b.message.admin.controller;

import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.b2b.bean.ResultBase;
import com.b2b.constant.ResultEnum;
import com.b2b.message.admin.bean.UserBean;
import com.b2b.message.admin.constant.Constant;
import com.b2b.utils.Tools;
import com.b2b.utils.ValidatorCodeUtil;
import com.b2b.utils.ValidatorCodeUtil.ValidatorCode;

/**
 * 版权：上海极和信息科技有限公司
 * 功能：首页
 * 作者：朱伟峰
 * 邮箱：zhuweifeng24@gmail.com
 * 日期：2018年3月23日
 */
@Controller
public class IndexController extends SuperController
{
	private static final Logger logger = LoggerFactory.getLogger(IndexController.class);
	
	// 默认访问
	@RequestMapping("/")
	public String main()
	{
		return login();
	}
		
	// 首页
	@RequestMapping(value = "/index")
	public String index()
	{
		UserBean userBean = super.getUserBean();
		if (userBean != null)
		{
			session.setAttribute(Constant.SESSION_USER, userBean);
		}
		return "/index";
	}
	
	// 我的主页
	@RequestMapping(value = "/home")
	public String home()
	{
		return "/home";
	}

	// 登录
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login()
	{
		if (super.getSubject().isAuthenticated())
			return "redirect:index";
		return "/login";
	}
	
	/**
	 * ajax登录请求
	 * @param username
	 * @param password
	 * @return
	 */
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String submitLogin(@RequestParam("username")String username, 
			@RequestParam("password")String password, @RequestParam("verity")String verity, 
			@RequestParam("rememberMe")boolean rememberMe)
	{
		if (Tools.isTrimEmpty(username))
		{
			request.setAttribute("errMsg", ResultEnum.ERR_2005.getMessage());
			return "/login";
		}
		if (Tools.isTrimEmpty(password))
		{
			request.setAttribute("errMsg", ResultEnum.ERR_2003.getMessage());
			return "/login";
		}
		if (Tools.isTrimEmpty(verity))
		{
			request.setAttribute("errMsg", ResultEnum.ERR_2025.getMessage());
			return "/login";
		}
		verity = verity.toUpperCase();
		
		String vcodeSession = (String) super.session.getAttribute(Constant.SESSION_VALIDCODE);
		if (Tools.isTrimEmpty(vcodeSession))
		{
			request.setAttribute("errMsg", ResultEnum.ERR_2026.getMessage());
			return "/login";
		}
		if (!verity.equals(vcodeSession))
		{
			request.setAttribute("errMsg", ResultEnum.ERR_2027.getMessage());
			return "/login";
		}

		ResultBase result = new ResultBase();
		
		try
		{
			UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);
			SecurityUtils.getSubject().login(token);
			result.success();
			super.session.removeAttribute(Constant.SESSION_VALIDCODE);
		}
		catch (Exception e)
		{
			logger.error("", e);
			request.setAttribute("errMsg", e.getMessage());
			return "/login";
		}
		return "redirect:index";
	}
	
	// 错误页面
	@RequestMapping(value="/error/{id}")
	public String error(@PathVariable int id)
	{
		switch (id)
		{
			case 401:
				return "/error/401";
			case 404:
				return "/error/404";
			case 500:
				return "/error/500";
			default:
				break;
		}
		return "/error/error";
	}

	/**
	 * 退出
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/logout")
	public ResultBase logout()
	{
		try
		{
			super.session.removeAttribute(Constant.SESSION_VALIDCODE);
			super.session.removeAttribute(Constant.SESSION_USER);
			SecurityUtils.getSubject().logout();
		}
		catch (Exception e)
		{
			logger.error("", e);
			return super.resultCatch();
		}
		return super.resultSuccess();
	}

	// 生成验证码
	@ResponseBody
	@RequestMapping(value = "/validcode")
	public void validcode()
	{
		ServletOutputStream sos = null;
		try
		{
			ValidatorCode codeUtil = ValidatorCodeUtil.getCode();
			super.session.setAttribute(Constant.SESSION_VALIDCODE, codeUtil.getCode().toUpperCase());
			// 禁止图像缓存。
			super.response.setHeader("Pragma", "no-cache");
			super.response.setHeader("Cache-Control", "no-cache");
			super.response.setDateHeader("Expires", 0);
			super.response.setContentType("image/jpeg");
			sos = super.response.getOutputStream();
			ImageIO.write(codeUtil.getImage(), "jpeg", sos);
			sos.flush();
			sos.close();
		}
		catch (Exception e)
		{
			logger.error("", e);
		}
		finally
		{
			try
			{
				if (sos != null)
				{
					sos.close();
				}
			}
			catch (IOException e)
			{
				logger.error("", e);
			}
		}
	}
	
}
